package com.ewili.x.special.utils;

import com.ewili.framework.utils.DateUtils;
import com.ewili.framework.utils.ExceptionUtils;
import com.ewili.framework.utils.StringUtils;
import com.ewili.x.special.vo.SeasonVo;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public final class WangYiUtils {

    public static List<SeasonVo> getSeason(String url, String keyWords) {

        List<SeasonVo> seasonVos = new ArrayList<>();

        Connection connection = Jsoup.connect(url);
        try {
            Document document = connection.get();
            Elements elements = document.getElementsByClass("title_01");
            for (Element element : elements) {
                String content = element.toString();
                if (!StringUtils.contains(content, keyWords)) {
                    continue;
                }
                Elements subElements = element.getElementsByTag("option ");
                for (Element subElement : subElements) {
                    Date season = DateUtils.parse(subElement.text(), DateUtils.yyyy_MM_dd);
                    String subDate = subElement.attr("value");
                    String[] dates = subDate.split(",");
                    Date endDate = DateUtils.parse(dates[0], DateUtils.yyyy_MM_dd);
                    Date startDate = DateUtils.parse(dates[1], DateUtils.yyyy_MM_dd);

                    SeasonVo seasonVo = new SeasonVo();
                    seasonVo.setSeason(season);
                    seasonVo.setStartDate(startDate);
                    seasonVo.setEndDate(endDate);
                    seasonVos.add(seasonVo);

                }
            }
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }
        return seasonVos;
    }

}
